package cool.taomu.toolkit.platform.controller

import java.io.InputStream
import java.nio.file.FileSystemNotFoundException
import javax.inject.Inject
import javax.ws.rs.GET
import javax.ws.rs.Path
import javax.ws.rs.PathParam
import javax.ws.rs.core.Response
import javax.ws.rs.core.StreamingOutput
import org.apache.commons.vfs2.FileObject
import org.apache.commons.vfs2.FileSystemException
import org.apache.commons.vfs2.FileSystemManager
import org.slf4j.LoggerFactory

@Path("static")
class StaticResource {
	val static LOG = LoggerFactory.getLogger(StaticResource)

	@Inject
	FileSystemManager fsManager

	@GET
	@Path("{filename: .+}")
	def Response getStaticFile(@PathParam("filename") String filename) {
		LOG.info("获取资源文件:{}", filename);
		if (filename === null || filename.isEmpty()) {
			return Response.status(Response.Status.NOT_FOUND).build();
		}
		var String resourcePath = String.format("res://static/%s", filename); // 使用"res:"协议指向classpath
		try {
			LOG.debug("解析res协议中的文件:{}", resourcePath)
			return getStaticResource(filename, resourcePath)
		} catch (FileSystemException|FileSystemNotFoundException e) {
			LOG.debug("解析file协议中的文件:{}", resourcePath, e)
			resourcePath = String.format("file://%s/static/%s", System.getProperty("user.dir"), filename);
			try {
				return getStaticResource(filename, resourcePath)
			} catch (FileSystemException|FileSystemNotFoundException exx) {
				LOG.debug("staticResource error:{}", resourcePath, exx)
				return Response.status(Response.Status.NOT_FOUND).build();
			}
		}
	}

	protected def Response getStaticResource(String filename, String resourcePath) {
		try {
			var FileObject fileObject = fsManager.resolveFile(resourcePath);
			if (!fileObject.exists()) {
				LOG.debug("VFS加载文件：{} 不存在，资源路径：{}", filename, resourcePath);
				return Response.status(Response.Status.NOT_FOUND).build();
			}
			LOG.debug("VFS加载文件：{}", filename, fileObject.path);
			val fileContent = fileObject.getContent();
			val InputStream fileStream = fileContent.getInputStream()

			LOG.debug("VFS加载文件 {} 成功 {} ", filename, fileObject.path);
			return this.loadFile(fileStream, filename);
		} catch (FileSystemException e) {
			LOG.debug("获取文件 {} 错误", resourcePath);
			throw new FileSystemException(e);
		}
	}

	private def Response loadFile(InputStream fileStream, String filename) {
		LOG.debug("返回找到的文件:{}", filename);
		if (fileStream === null) {
			return Response.status(Response.Status.NOT_FOUND).build();
		}

		var StreamingOutput stream = [ output |
			var buffer = newByteArrayOfSize(1024)
			var int length;
			while ((length = fileStream.read(buffer)) != -1) {
				output.write(buffer, 0, length);
			}
			fileStream.close();
		]
		// 根据文件扩展名设置合适的MIME类型
		var String mimeType = "application/octet-stream";
		if (filename.endsWith(".js") || filename.endsWith(".json")) {
			mimeType = "application/javascript";
		} else if (filename.endsWith(".css")) {
			mimeType = "text/css";
		} else if (filename.endsWith(".html")) {
			mimeType = "text/html;charset=UTF-8";
		}

		return Response.ok(stream, mimeType).build();
	}
}